package com.lemon.downloadandupload;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.LineSeparator;
import com.google.api.services.youtube.YouTube;
import com.lemon.config.UpConfig;
import com.lemon.dto.MyVideo;
import com.lemon.utils.BilibiliUtil;
import com.lemon.utils.YoutubeUtil;
import com.lemon.vo.UpInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import sun.security.action.GetPropertyAction;

import java.io.File;
import java.security.AccessController;
import java.util.*;

@Component
@Slf4j
public class Task implements ApplicationContextAware {

    @Value("#{${keyWords}}")
    Map<String, String> keywords;

    @Value("${bvid-path}")
    String bvidPath;

    @Autowired
    BilibiliUtil bilibiliUtil;

    @Autowired
    YoutubeUtil youtubeUtil;

    ApplicationContext applicationContext;

    final static public String line = AccessController.doPrivileged(new GetPropertyAction("line.separator"));

    @Autowired
    UpConfig upConfig;

    /**
     * 根据关键字搜索搬运视频
     */
    //@Scheduled(cron = "0 0 0/2 * * ?")
    public void downUpByKeyWord(){
        Map<String, YouTube> youTubeMap = applicationContext.getBeansOfType(YouTube.class);
        for (Map.Entry<String, String> entry : keywords.entrySet()) {
            String value = entry.getValue();
            String key = entry.getKey();
            YouTube youTube = youTubeMap.get(key);
            if (youTube == null) {
                log.info("暂无频道！");
                continue;
            }
            // 加载上传过的bvid
            Set<String> bvidSet = loadBvid(key);
            // 增量bvid
            Set<String> incrementBvid = new HashSet<>();
            // 记录上传是视频的数量
            int count = 0;
            List<MyVideo> myVideos = bilibiliUtil.getMyVideos(value, bvidSet);
            for (MyVideo myVideo : myVideos) {
                boolean flag = youtubeUtil.upVideoToYoutube(youTube, myVideo);
                if (flag) {
                    ++count;
                    // 记录上传的视频的bvid 在下载的时候用来防止重复下载
                    incrementBvid.add(myVideo.getBvid());
                }
            }
            log.info("频道信息key:{}, val:{} 视频上传成功数量:{}", key, value,count);
            // 增量数据追加到文件中
            appendBvidFile(incrementBvid, key);
        }
    }

    /**
     * 根据up主信息搬运视频
     *
     */
    @Scheduled(cron = "0 0 2,6,21 * * ?")
    public void downUpByUid(){
        Map<String, YouTube> youTubeMap = applicationContext.getBeansOfType(YouTube.class);
        Map<String, UpInfo> upMap = upConfig.getUpMap();

        for (Map.Entry<String, UpInfo> entry : upMap.entrySet()) {
            UpInfo value = entry.getValue();
            String key = entry.getKey();
            YouTube youTube = youTubeMap.get(value.getChannel());
            if (youTube == null) {
                log.info("暂无频道！");
                continue;
            }
            // 加载上传过的bvid
            Set<String> bvidSet = loadBvid(value.getChannel());
            // 增量bvid
            Set<String> incrementBvid = new HashSet<>();
            // 记录上传视频的数量
            int count = 0;
            List<MyVideo> myVideos = bilibiliUtil.getMyVideosByUid(value.getUid(),value.getName(), value.getTag(), bvidSet);
            for (MyVideo myVideo : myVideos) {
                boolean flag = youtubeUtil.upVideoToYoutube(youTube, myVideo);
                if (flag) {
                    ++count;
                    // 记录上传的视频的bvid 在下载的时候用来防止重复下载
                    incrementBvid.add(myVideo.getBvid());
                }
            }
            log.info("频道信息key:{}, val:{} 视频上传成功数量:{}", value.getChannel(), value,count);
            // 增量数据追加到文件中
            appendBvidFile(incrementBvid, value.getChannel());
        }
    }


    private void appendBvidFile(Set<String> incrementBvid, String key) {
        File file = new File(bvidPath + key + "-bvid.txt");
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (Exception e) {
                log.error("bvid文件创建失败.", e);
            }
        }
        FileUtil.appendLines(incrementBvid, file, "UTF-8");

    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public Set<String> loadBvid(String key){
        HashSet<String> result = new HashSet<>();
        File file = new File(bvidPath + key + "-bvid.txt");
        if (!file.exists()) {
            return result;
        }
        String string = FileUtil.readString(file, "utf-8");
        String[] split = string.split(line);
        result.addAll(Arrays.asList(split));
        return result;
    }


}
